var api = require('../config/api.js')

var app = getApp()

function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()
  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}
/**
 * 封封微信的的request
 */

function request(url, data = {}, method = 'GET') {
  return new Promise(function (resolve, reject) {
    let topic = uni.getStorageSync('topic')
    let send = data
    if (topic) {
      send.topicId = topic.id
    }
    uni.request({
      url: url,
      data: send,
      method: method,
      header: {
        'Content-Type': 'application/json',
        'X-Dts-Token': uni.getStorageSync('token'),
      },
      success: function (res) {
        if (res.statusCode == 200) {
          if (res.data.errno == 501) {
            // 清除登录相关内容
            try {
              uni.removeStorageSync('userInfo')
              uni.removeStorageSync('token')
              uni.removeStorageSync('tabBotName')
            } catch (e) {
              // Do something when catch error
            } // 切换到登录页面


            if (location.href.includes('/pages/goods/goods?')) {
              uni.setStorageSync('goodsIdToLogin', location.href)
            }

            uni.redirectTo({
              url: '/pages/auth/login/login',
            })
          } else {
            if (res.data.errno == 0) {
              resolve(res.data)
            } else {
              reject(res.data)
            }
          }
        } else {
          reject(res.errMsg)
        }
      },
      fail: function (err) {
        reject(err)
      },
    })
  })
}

function redirect(url) {
  //判断页面是否需要登录
  if (false) {
    uni.redirectTo({
      url: '/pages/auth/login/login',
    })
    return false
  } else {
    uni.redirectTo({
      url: url,
    })
  }
}

function showErrorToast(msg) {
  uni.showToast({
    title: msg,
    image: '/static/static/images/icon_error.png',
  })
}

function jhxLoadShow(message) {
  if (uni.showLoading) {
    // 基础库 1.1.0 微信6.5.6版本开始支持，低版本需做兼容处理
    uni.showLoading({
      title: message,
      mask: true,
    })
  } else {
    // 低版本采用Toast兼容处理并将时间设为20秒以免自动消失
    uni.showToast({
      title: message,
      icon: 'loading',
      mask: true,
      duration: 20000,
    })
  }
}

function jhxLoadHide() {
  if (uni.hideLoading) {
    // 基础库 1.1.0 微信6.5.6版本开始支持，低版本需做兼容处理
    uni.hideLoading()
  } else {
    uni.hideToast()
  }
}

module.exports = {
  formatTime,
  request,
  redirect,
  showErrorToast,
  jhxLoadShow,
  jhxLoadHide,
}
